﻿$(document).ready(function() {
    $('.btnView').click(function() {
        var tblTarget = $('#tblRuleInfo > tbody');
        var tRowTarget = tblTarget.children('tr');

        var tRow = $(this).closest('tr');
        var tCell = tRow.children('td');

        var ruleCategory = tCell.eq(0).text();
        var ruleControl = tCell.eq(1).text();
        var conds1 = tCell.eq(2).text();
        var conds2 = tCell.eq(3).text();
        var fixdisc = tCell.eq(4).text();
        var scenario = tCell.eq(5).text();

        var optScenario = "<option value='0'>--- Select ---</option>";
        var scenarioLen = parseInt(scenario);
        for (var idx = 0; idx < scenarioLen; idx++) {
            var tmpOpt = '<option value="' + (idx + 1) + '">';
            tmpOpt += (idx + 1) + '</option>';

            optScenario += tmpOpt;
        }

        $('#cbScenario').html(optScenario);
        tRowTarget.eq(2).children('td').eq(2).find('span').text(ruleControl);
        tRowTarget.eq(3).children('td').eq(2).find('span').text(conds1);
        tRowTarget.eq(4).children('td').eq(2).find('span').text(conds2);
        tRowTarget.eq(5).children('td').eq(2).find('span').text(fixdisc);
        tRowTarget.eq(6).children('td').eq(2).find('span').text(ruleCategory);
        tRowTarget.eq(7).children('td').eq(2).find('span').text(scenario);
        $('#divAdd, #tblRules').fadeOut(100, function() {
            $('#ruleInfo').fadeIn(300);
        });

    });

    $('#cbScenario').change(function() {
        var thisval = $(this).val();
        var tblTarget = $('#tblRuleInfo > tbody');
        var tRowTarget = tblTarget.children('tr');

        for (var idx = 2; idx < 11; idx++) {
            tRowTarget.eq(idx).children('td').eq(2).find('span').hide();
        }
        $('#btnEdit, #btnDelScenario').hide();
        if (!(thisval == '0' || thisval == 0)) {
            var ruleCategory = tRowTarget.eq(6).children('td').eq(2).find('span').text();
            var ruleValue = tRowTarget.eq(3).children('td').eq(2).find('span').text();
            getExtRuleInfo(ruleCategory, getRuleValue(ruleValue), thisval);
            for (var idx = 2; idx < 11; idx++) {
                tRowTarget.eq(idx).children('td').eq(2).find('span').fadeIn(300);
            }
            $('#btnEdit, #btnDelScenario').fadeIn(300);
        }
    });

    $('#btnClose').click(function() {
        var tblTarget = $('#tblRuleInfo > tbody');
        var tRowTarget = tblTarget.children('tr');
        $('#ruleInfo').fadeOut(100, function() {
            for (var idx = 2; idx < 11; idx++) {
                tRowTarget.eq(idx).children('td').eq(2).find('span').text("").hide();
            }
            $('#btnEdit, #btnDelScenario').hide();
            $('#divAdd, #tblRules').fadeIn(300);
        });
    });

    $('#imgInfo1').click(function() {
        var txtTitle = 'Override / Fixed Discount';
        var txtBody = '<p>If the value is YES then discount amount will be fixed as ' +
            'showed in <strong>conditions</strong><br /><br />' +
            'System will automatically locked (override) ' +
            'discount field for all products whenever user create new request.';

        createHelp(txtTitle, txtBody, 245, 300);
    });

    $('#imgInfo2').click(function() {
        var txtTitle = 'Approval Layer Key';
        var txtBody = '<p>Layer number where the approval path should be created.</p>';
        txtBody += '<strong>Note:</strong><br />';
        txtBody += 'This Layer Key can be used as an information or guide in creating approval path.';

        createHelp(txtTitle, txtBody, 245, 300);
    });

    $('#imgInfo3').click(function() {
        var txtTitle = 'Total Approval Layers';
        var txtBody = '<p>Total numbers of approval layers in Layer Editor.</p>';
        txtBody += '<strong>Note:</strong><br />';
        txtBody += 'The total layer numbers will automatically changed when ' +
            'you add new layers in Approval Layer Editor.';

        createHelp(txtTitle, txtBody, 236, 300);
    });

    $('#btnAddRule').click(function() {
        window.location.href = 'AddRules.aspx';
    });

    $('#btnEdit').click(function() {
        var tblTarget = $('#tblRuleInfo > tbody');
        var tRowTarget = tblTarget.children('tr');
        var ruleCategory = tRowTarget.eq(6).children('td').eq(2).find('span').text();
        var rValue = tRowTarget.eq(3).children('td').eq(2).find('span').text();
        var rMaxLayers = tRowTarget.eq(9).children('td').eq(2).find('span').text();
        var ruleValue = getRuleValue(rValue);
        var Scenario = $('#cbScenario').val();

        GetLayerData(ruleCategory, ruleValue, Scenario, rMaxLayers);
    });

    $('#btnDelScenario').click(function() {
        var tblTarget = $('#tblRuleInfo > tbody');
        var tRowTarget = tblTarget.children('tr');
        var ruleCategory = tRowTarget.eq(6).children('td').eq(2).find('span').text();
        var rValue = tRowTarget.eq(3).children('td').eq(2).find('span').text();
        var ruleValue = getRuleValue(rValue);
        var Scenario = $('#cbScenario').val();

        if (confirm("Delete this Rule (Category: " + ruleCategory + ", Scenario: " + Scenario + ")?") == true) {
            var strData = "{'RuleCategory':'" + ruleCategory;
            strData += "', 'RuleValue':'" + ruleValue;
            strData += "', 'RuleScenario':'" + Scenario + "'}";
            $.ajax({
                type: "POST",
                url: "ApprovalRule.aspx/DeleteRuleScenario",
                contentType: "application/json;charset=utf-8",
                data: strData,
                datatype: "json",
                success: function(data) {
                    if (data.d == "success") {
                        alert("Delete data success!");
                        window.location.href = "ApprovalRule.aspx";
                    } else {
                        alert(data.d);
                    }
                }
            });
            return false;
        }
    });

    $('#btnAddLayer').click(function() {
        var layerParent = $('#rule-wrapper');
        var layerRuleBox = layerParent.children('.rule-box');
        var layerLength = layerRuleBox.length;
        var arrowDown = layerRuleBox.eq((layerLength - 1)).children().eq(1);
        arrowDown.show();

        var newLayer = addLayer(layerLength);
        $('#rule-wrapper').append(newLayer);
    });

    $('#rule-wrapper').on('click', '.btnRemoveLayer', function() {
        var topParent = $('#rule-wrapper').children('.rule-box');
        var topParentLength = topParent.length;
        var thisParent = $(this).parent().parent();
        var getLength = thisParent.index();
        var prevArrow = $('#rule-wrapper').children('.rule-box').eq((getLength - 1)).children('.ruleDown');
        topParent.eq(getLength).remove();
        if ((getLength - 1) >= 1 && topParentLength == (getLength + 1)) {
            prevArrow.hide();
        }
        var newLength = topParentLength - 1;
        if (newLength > 2) {
            var newIdx = 1;
            for (var idx = 2; idx < (newLength + 1); idx++) {
                var newTitle = 'Approval Layer: ';
                var ctrlBox = topParent.eq(idx).children().children().eq(0).children().eq(0);
                var isVisible = ctrlBox.is(":visible");
                if (isVisible) {
                    newIdx++;
                    newTitle += newIdx;
                } else {
                    continue;
                }
                ctrlBox.text(newTitle);
            }
        }
    });

    $('#btnCancel').click(function() {
        $('#divLayerEditor').fadeOut(100, function() {
            $('#divRules').fadeIn(300);
        });
    });

    $('#rule-wrapper').on('click', '.btnAdd', function() {
        var thisParent = $(this).parentsUntil('div#rule-wrapper').eq(2);
        var thisIndex = thisParent.index();
        var cbAdd = $(this).next();
        var strFindBy = cbAdd.val();
        if (strFindBy == 1) {
            var strData = '{"Search": ""}';
            var postTo = "ApprovalRule.aspx/LoadRole";
            $.ajax({
                type: "POST",
                url: postTo,
                data: '{"Search": ""}',
                contentType: "application/json;charset=utf-8",
                datatype: "json",
                success: function(data) {
                    var content = processJSON(data.d, thisIndex);
                    if (typeof content != 'undefined' || content != '') {
                        dialogForm(strFindBy, thisIndex, content);
                        $("#ModalDialog").showCZDialog({
                            width: 400,
                            height: 350
                        });
                    }
                }
            });
            return false;
        } else {
            dialogForm(strFindBy, thisIndex);
            $("#ModalDialog").showCZDialog({
                width: 400,
                height: 350
            });
        }
    });

    $('#rule-wrapper').on('click', '.imgDel', function() {
        var thisRow = $(this).closest('tr');
        var thisParent = thisRow.parent();
        thisRow.remove();
        var countRows = thisParent.children('tr').length;
        if (countRows > 0) {
            for (var idx = 0; idx < (countRows); idx++) {
                var addOddEven = ((idx % 2) == 0) ? 'odd' : 'even';
                thisParent.children('tr').eq(idx).attr("class", addOddEven);
            }
        } else {
            thisParent.append('<tr><td colspan="3">No data</td></tr>');
        }
    });

    $('#ModalDialog').on('keypress', '#autocomplete1', function(e) {
        if (e.keyCode == 13) {
            var thisParent = $(this).parent();
            var tmpVal = $(this).val();
            if (typeof tmpVal == 'undefined' || tmpVal == '') {
                alert('Please type keywords!');
                return false;
            } else {
                searchData(thisParent, tmpVal);
            }
        }
    });

    $('#ModalDialog').on('click', '#btnSearch', function() {
        var thisParent = $(this).parent();
        var tmpVal = $(this).prev().val();
        if (typeof tmpVal == 'undefined' || tmpVal == '') {
            alert('Please type keywords!');
            return false;
        } else {
            searchData(thisParent, tmpVal);
        }
    });

    $('#btnSaveLayer').click(function() {
        var question = "Update Approval Layers?";
        if (confirm(question) == true) {
            //var topParent = $('#rule-wrapper').children('.rule-box');
            //var childLength = topParent.length;

            var tblTarget = $('#tblRuleInfo > tbody');
            var tRowTarget = tblTarget.children('tr');
            var ruleCat = tRowTarget.eq(6).children('td').eq(2).find('span').text();
            var tmpRuleVal = tRowTarget.eq(3).children('td').eq(2).find('span').text();
            var ruleVal = getRuleValue(tmpRuleVal);
            var tmpRuleValExt = tRowTarget.eq(4).children('td').eq(2).find('span').text();
            //var ruleValExt = (typeof tmpRuleValExt == 'undefined' || tmpRuleValExt == '') ? '' : '"' + getRuleValue(tmpRuleValExt) + '"';
            var ruleValExt = (typeof tmpRuleValExt == 'undefined' || tmpRuleValExt == '') ? '' : getRuleValue(tmpRuleValExt);
            
            //var tblInfo = $('#tblRuleInfo > tbody').children('tr');
            var _RuleControl = ruleCat;
            var _RuleValue = ruleVal;
            var _RuleValueExt = ruleValExt;
            var _RuleScenario = $('#cbScenario').val();

            var divParent = $('#rule-wrapper');
            var divRules = divParent.children();
            var divRulesLength = divRules.length;
            var divContent = divRules.children('.rule-content').children('.rule-list-box');
            var tblContent = divContent.children('table');
            var tblContentLength = divRules.length;

            var chkLength = tblContent.length;
            var isNotEmpty = true;
            for (var iXs1 = 0; iXs1 < chkLength; iXs1++) {
                var chkTbl = tblContent.eq(iXs1);
                var chkRows = chkTbl.children('tbody').children('tr');
                var chkRowLength = chkRows.length;
                for (var iXs2 = 0; iXs2 < chkRowLength; iXs2++) {
                    var chkTD = chkRows.eq(iXs2).children('td').length;
                    if (chkTD <= 1) {
                        isNotEmpty = false;
                        break;
                    }
                }
            }

            if (isNotEmpty == true) {
                var _StepSeq = [];
                var _CurrentStep = [];
                var _NextStep = [];
                var _ActorCategory = [];
                for (var idx1 = 0; idx1 < tblContentLength; idx1++) {
                    var tRow = tblContent.eq(idx1).children('tbody').children('tr');
                    var tRowLength = tRow.length;

                    _StepSeq[idx1] = [];
                    _CurrentStep[idx1] = [];
                    _NextStep[idx1] = [];
                    _ActorCategory[idx1] = [];
                    for (var idx2 = 0; idx2 < tRowLength; idx2++) {
                        var tDval = tRow.eq(idx2).children('td');
                        var stepVal = tDval.eq(1).children().eq(0).text();
                    }

                    var tblNext = tblContent.eq((idx1 + 1)).children('tbody');
                    var tblNextRow = tblNext.children('tr');
                    var tblNextRowLength = tblNextRow.length;
                    if (idx1 < (tblContentLength - 1)) {
                        for (var idx3 = 0; idx3 < tRowLength; idx3++) {
                            var tDPrev1 = tRow.eq(idx3).children('td');
                            for (var idx4 = 0; idx4 < tblNextRowLength; idx4++) {
                                var tDvalNext = tblNextRow.eq(idx4).children('td');
                                var tDnextVal = tDvalNext.eq(1).children().eq(0).text();
                                var prevVal1 = tDPrev1.eq(1).children().eq(0).text();
                                var nextVal = tDnextVal;
                                var tmpRolePrev1 = tDPrev1.eq(0).children().eq(1).text();
                                var sRolePrev1 = (tmpRolePrev1 == 'Role') ? 'ROLE' : 'UNAME';

                                _StepSeq[idx1].push((idx1 + 1));
                                _CurrentStep[idx1].push(prevVal1);
                                _NextStep[idx1].push(nextVal);
                                _ActorCategory[idx1].push(sRolePrev1);
                            }
                        }
                    } else if (idx1 == (tblContentLength - 1)) {
                        for (var idx5 = 0; idx5 < tRowLength; idx5++) {
                            var tDPrev2 = tRow.eq(idx5).children('td');
                            var prevVal2 = tDPrev2.eq(1).children().eq(0).text();
                            var tmpRolePrev2 = tDPrev2.eq(0).children().eq(1).text();
                            var sRolePrev2 = (tmpRolePrev2 == 'Role') ? 'ROLE' : 'UNAME';
                            var lastStep = "0";

                            _StepSeq[idx1].push((idx1 + 1));
                            _CurrentStep[idx1].push(prevVal2);
                            _NextStep[idx1].push(lastStep);
                            _ActorCategory[idx1].push(sRolePrev2);
                        }
                    }
                }

                var data_RuleControl = '{"RuleControl":"' + _RuleControl + '", ';
                var data_RuleValue = '"RuleValue":"' + _RuleValue + '", ';
                var data_RuleValueExt = '"RuleValueExt":"' + _RuleValueExt + '", ';
                var data_RuleScenario = '"RuleScenario":"' + _RuleScenario + '", ';
                var data_StepSeq = '"StepSeq": ["' + _StepSeq + '"], ';
                var data_CurrentStep = '"CurrentStep": ["' + _CurrentStep + '"], ';
                var data_NextStep = '"NextStep": ["' + _NextStep + '"], ';
                var data_ActorCategory = '"ActorCategory": ["' + _ActorCategory + '"]}';

                var sendData = data_RuleControl + data_RuleValue + data_RuleValueExt + data_RuleScenario + data_StepSeq +
                    data_CurrentStep + data_NextStep + data_ActorCategory;
                //console.log(sendData);
                updateLayer(sendData);
            } else {
                alert('Update failed: One or more layers are still empty!');
            }
        }
    });

});

function updateLayer(details) {
    $.ajax({
        type: "POST",
        url: "ApprovalRule.aspx/UpdateLayer",
        data: details,
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            //console.log(data);
            if (data.d == 'success') {
                alert("Update data success!");
                window.location.href = "ApprovalRule.aspx";
            } else {
                alert(data.d);
            }
        }
    });
    return false;
}

function searchData(container, ctrlValue) {
    var findTbl = container.next();
    var idTbl = findTbl.attr("id");
    var postFncTo = (idTbl == 'tblRoles') ? 'LoadRole' : 'LoadUser';
    var postTo = 'ApprovalRule.aspx/' + postFncTo;
    var thisVal = (typeof ctrlValue == 'undefined' || ctrlValue == '') ? '' : ctrlValue;
    var strData = '{"Search": "' + thisVal + '"}';
    var thisIndex = container.children().eq(2).text();
    var tblBody = findTbl.children('tbody');
    $.ajax({
        type: "POST",
        url: postTo,
        data: strData,
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            tblBody.html("");
            var content = processJSON(data.d, thisIndex);
            tblBody.html(content);
        }
    });
    return false;
}

function insertRow(sender, id, name) {
    var parentDiv = $('#rule-wrapper').children('.rule-box').eq(sender);
    var childDiv = parentDiv.children().find('table');
    var tblBody = childDiv.children('tbody');
    var tblRows = tblBody.children('tr');
    var tblRowsCount = tblRows.length;

    var isNoData = false;
    for (var idx = 0; idx < tblRowsCount; idx++) {
        var tblColCount = tblRows.eq(idx).children('td').length;
        if (tblColCount <= 1) {
            isNoData = true;
        }
    }

    var btnDel = '<img class="imgDel" src="images/delete.png" style="cursor:pointer;width:14px;height:14px;border:0;" title="Remove" />';
    var cbAdd = parentDiv.children().find('.cbAdd');
    var actCat = (cbAdd.val() == 1) ? "Role" : "Person";
    var tmpNewRow = '<td><span style="display:none">' + sender +
        '</span><span>' + actCat + '</span></td>' +
        '<td style="text-align:left;"><span style="display:none">' + id +
        '</span><span>' + name + '</span></td>' +
        '<td>' + btnDel + '</td></tr>';

    if (isNoData == true) {
        tblBody.html("");

        var tmpTRNew = '<tr class="odd">';
        var newRow = tmpTRNew + tmpNewRow;
        tblBody.html(newRow);
    } else {
        var isExist = false;
        var tblRowChilds = tblRows.children('td');
        for (var i = 0; i < tblRowsCount; i++) {
            var currentID = tblRows.eq(i).children('td').eq(1).children('span').eq(0).text();
            if (currentID == id) {
                isExist = true;
                break;
            }
        }

        if (!isExist) {
            var setClass = ((tblRowsCount % 2) == 0) ? 'odd' : 'even';
            var tmpTRNew = '<tr class="' + setClass + '">';
            var newRow = tmpTRNew + tmpNewRow;
            tblBody.append(newRow);
        } else {
            alert('Role and/or Person is already listed!');
        }
    }

    $('#ModalDialog').closeCZDialog();
}

function dialogForm(mode, sender, content) {
    var sMode = (typeof mode == 'undefined' || mode == '') ? '' : mode;
    var sContent = (typeof content == 'undefined' || content == '') ? '' : content;
    var sSender = (typeof sender == 'undefined' || sender == '') ? '0' : sender;
    var tblID = (sMode == '') ? 'tblUsers' : ((sMode == '2') ? 'tblUsers' : 'tblRoles');
    //var thTitle = (sMode == '') ? 'Username' : ((sMode == '2') ? 'Username' : 'Role Alias');
    var search = '<div style="margin:5px 0;">' +
        '<input id="autocomplete1" type="text" placeholder="Type & Enter" value="" style="width:280px;" />' +
        '<div id="btnSearch" class="btnSmall">Search</div><span style="display:none;">' + sSender + '</span>' +
        '</div>';
    var tbl1 = '<table id="' + tblID + '" class="tblstyle" style="border:0; width:100%;">' +
            '<thead style="display:block;">' +
            '    <tr>' +
            '        <th style="table-layout: fixed; width:120px;">Role</th>' +
            '        <th style="table-layout: fixed; width:240px;">Name</th>' +
            '    </tr>' +
            '</thead>' +
            '<tbody style="display:block; height:240px; overflow-y:scroll;">';
    var tbl2 = '</tbody></table>';

    var result = tbl1 + search + sContent + tbl2;
    $('#ModalDialog').html(result);
}

function processJSON(response, sender) {
    var result = "";
    var dataLength = response.length;
    if (dataLength > 0) {
        var tdID = '<td style="table-layout:fixed;width:129px;">';
        var tdName = '<td style="table-layout:fixed;width:239px;">';
        var tdEnd = '</td>';
        for (var idx = 0; idx < dataLength; idx++) {
            var isOddorEven = (idx % 2 == 0) ? 'odd' : 'even';
            var tmpIDHide = "";
            var sentIDHide = "";
            if (!(response[idx].ID == null || typeof response[idx].ID == 'undefined' || response[idx].ID == '')) {
                tmpIDHide = '<span style="display:none;">' + response[idx].ID + '</span>';
                sentIDHide = response[idx].IDHide;
            }
            var addScript = ' onmouseover="this.style.background=\'#ccc\'" onMouseout="this.style.background=\'\'" ';
            var strID = response[idx].ID;
            var strData = "'" + strID + "','" + response[idx].Name + "'";
            var trStart = '<tr style="cursor:pointer" class="tRow ' + isOddorEven + '" onclick="insertRow(' +
                sender + ',' + strData + ');" ' + addScript + ' >';
            var trEnd = '</tr>';
            var tmpID = trStart + tdID + tmpIDHide + response[idx].Role + tdEnd;
            var tmpName = tdName + response[idx].Name + tdEnd + trEnd;

            result += tmpID + tmpName;
        }
    } else {
        result = '<tr><td colspan="2" style="padding:30px 10px; text-align:center; width:348px">Data not found</td></tr>';
    }
    return result;
}

function addLayer(LayerNum) {
    var template = '<div class="rule-box">' +
        '<div class="rule-content">' +
        '    <div class="rule-header-box">' +
        '        <div class="rule-header">Approval Layer : ' + LayerNum + '</div>' +
        '        <div class="btnAdd btnSmall">Add</div>' +
        '        <select name="cbAdd" class="cbAdd">' +
        '           <option value="1">Role</option>' +
        '            <option value="2">Person</option>' +
        '        </select>' +
        '        <div class="cl_both"></div>' +
        '    </div>' +
        '    <div class="rule-list-box">' +
        '        <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
        '            <thead>' +
        '                <tr>' +
        '                    <th style="table-layout:fixed;width:60px;">Type</th>' +
        '                    <th>Name</th>' +
        '                    <th style="table-layout:fixed;width:30px;">Option</th>' +
        '                </tr>' +
        '            </thead>' +
        '            <tbody>' +
        '                <tr><td colspan="3">No data</td></tr>' +
        '            </tbody>' +
        '        </table>' +
        '    </div>' +
        '    <div class="btnRemoveLayer btnSmall">Remove Layer</div>' +
        '</div>' +
        '<div class="ruleDown" style="display:none;"></div>' +
        '</div>';
    return template;
}

function GetLayerData(ruleCtrl, ruleValue, ruleScenario, maxLayers) {
    var strData = "{'RuleCtrl':'" + ruleCtrl + "', 'RuleValue':'" + ruleValue +
        "', 'RuleScenario':'" + ruleScenario + "'}";
    $.ajax({
        type: "POST",
        url: "ApprovalRule.aspx/GetLayerList",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            var targetDIV = $('#rule-wrapper');
            targetDIV.html("");

            var dataLength = data.d.length;
            if (dataLength > 0) {
                for (var idx = 0; idx < dataLength; idx++) {
                    var isLast = (idx == (dataLength - 1)) ? true : false;
                    var _ruleID = data.d[idx].RuleID;
                    var _scenario = data.d[idx].Scenario;
                    var _seq = data.d[idx].Seq;
                    var _details = data.d[idx].Details;

                    var showTree = fillLayer(_seq, _details, isLast);
                    targetDIV.append(showTree);
                }
            } else {
                var showTreeEmpty = createLayers(maxLayers);
                targetDIV.html(showTreeEmpty);
            }
            $('#divRules').fadeOut(100, function() {
                $('#divLayerEditor').fadeIn(300);
            });
        }
    });
    return false;
}

function fillLayer(LayerIdx, LayerContent, isLast) {
    var btnDel = '<img class="imgDel" src="images/delete.png" style="cursor:pointer;width:14px;height:14px;border:0;" title="Remove" />';
    var cLength = LayerContent.length;
    var trContent = "";
    for (var idx = 0; idx < cLength; idx++) {
        var addOddEven = ((idx % 2) == 0) ? ' class="odd"' : ' class="even"';
        var actCat = (LayerContent[idx].ActorCategory == 'ROLE') ? 'Role' : 'Person';
        //var actName = '(' + LayerContent[idx].CurrentStep + ') ' + LayerContent[idx].ActorName;
        var tmpTD = '<tr ' + addOddEven + '><td><span style="display:none">' + LayerIdx +
            '</span><span>' + actCat + '</span></td>' +
            '<td style="text-align:left;"><span style="display:none">' + LayerContent[idx].CurrentStep +
            '</span><span>' + LayerContent[idx].ActorName + '</span></td>' +
            '<td>' + btnDel + '</td></tr>';
        trContent += tmpTD;
    }

    var Title = (LayerIdx == 1) ? "Requester:" : "Approval Layer: " + (LayerIdx - 1);
    var btnRemove = (LayerIdx <= 2) ? "" : '<div class="btnRemoveLayer btnSmall">Remove Layer</div>';
    var iconArrow = (isLast == false) ? '' : ' style="display:none;"';

    var template1 = '<div class="rule-box">' +
        '<div class="rule-content">' +
        '    <div class="rule-header-box">' +
        '        <div class="rule-header">' + Title + '</div>' +
        '        <div class="btnAdd btnSmall">Add</div>' +
        '        <select name="cbAdd" class="cbAdd">' +
        '           <option value="1">Role</option>' +
        '            <option value="2">Person</option>' +
        '        </select>' +
        '        <div class="cl_both"></div>' +
        '    </div>' +
        '    <div class="rule-list-box">' +
        '        <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
        '            <thead>' +
        '                <tr>' +
        '                    <th style="table-layout:fixed;width:60px;">Type</th>' +
        '                    <th>Name</th>' +
        '                    <th style="table-layout:fixed;width:30px;">Option</th>' +
        '                </tr>' +
        '            </thead>' +
        '            <tbody>';
    var template2 = '            </tbody>' +
        '        </table>' +
        '    </div>' + btnRemove +
        '</div>' +
        '<div class="ruleDown"' + iconArrow + '></div>' +
        '</div>';

    return template1 + trContent + template2;
}

function createLayers(layerNum) {
    var result = '<div class="rule-box">' +
       '     <div class="rule-content">' +
       '         <div class="rule-header-box">' +
       '             <div class="rule-header">Requester:</div>' +
       '             <div class="btnAdd btnSmall">Add</div>' +
       '             <select name="cbAdd" class="cbAdd">' +
       '                 <option value="1">Role</option>' +
       '                 <option value="2">Person</option>' +
       '             </select>' +
       '             <div class="cl_both"></div>' +
       '         </div>' +
       '         <div class="rule-list-box">' +
       '             <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
       '                 <thead>' +
       '                     <tr>' +
       '                         <th style="table-layout:fixed;width:60px;">Type</th>' +
       '                         <th>Name</th>' +
       '                         <th style="table-layout:fixed;width:30px;">Option</th>' +
       '                     </tr>' +
       '                 </thead>' +
       '                 <tbody>' +
       '                     <tr><td colspan="3">No data</td></tr>' +
       '                 </tbody>' +
       '             </table>' +
       '         </div>' +
       '     </div>' +
       '     <div class="ruleDown"></div>' +
       ' </div>';

    //var maxSteps = layerNum - 1;
    for (var idx = 0; idx < layerNum; idx++) {
        var iconArrow = (idx == (layerNum - 1)) ? ' style="display:none;"' : '';
        var keyLayer = (idx == 0) ? '' : '<div class="btnRemoveLayer btnSmall">Remove Layer</div>';
        //console.log("[" + idx + "] " + (idx + 1) + ": " + keyLayer);
        var tmpResult = '<div class="rule-box">' +
        '<div class="rule-content">' +
        '    <div class="rule-header-box">' +
        '        <div class="rule-header">Approval Layer : ' + (idx + 1) + '</div>' +
        '        <div class="btnAdd btnSmall">Add</div>' +
        '        <select name="cbAdd" class="cbAdd">' +
        '           <option value="1">Role</option>' +
        '            <option value="2">Person</option>' +
        '        </select>' +
        '        <div class="cl_both"></div>' +
        '    </div>' +
        '    <div class="rule-list-box">' +
        '        <table class="tblstyle" style="margin-bottom:5px;padding-bottom:0;">' +
        '            <thead>' +
        '                <tr>' +
        '                    <th style="table-layout:fixed;width:60px;">Type</th>' +
        '                    <th>Name</th>' +
        '                    <th style="table-layout:fixed;width:30px;">Option</th>' +
        '                </tr>' +
        '            </thead>' +
        '            <tbody>' +
        '                <tr><td colspan="3">No data</td></tr>' +
        '            </tbody>' +
        '        </table>' +
        '    </div>' + keyLayer +
        '</div>' +
        '<div class="ruleDown"' + iconArrow + '></div>' +
        '</div>';
        result += tmpResult;
    }

    return result;
}

function createHelp(helpTitle, helpText, helpHeight, helpWidth) {
    var dTitle = '<div style="border-bottom:1px dotted #000;padding:5px 0;font-size:14px;font-weight:bold;margin:10px;text-align:center;font-family:Arial">' +
        helpTitle + '</div>';
    var dContent = '<div style="font-size:12px;padding:0;margin:0 10px;color:#007FFF;">' +
        helpText + '</div>';
    var dButton = '<div id="closeHelpWrapper" style="position:absolute;bottom:10px;left:0;width:100%;text-align:center;">' +
        '<div id="closeHelp" class="btnSmall">Close</div>' +
        '</div>';
    var helpContent = dTitle + dContent + dButton;

    $('#ModalDialog').html(helpContent).showCZDialog({
        width: helpWidth, height: helpHeight, closeButton: '#closeHelp'
    });
    $('#divModalWrap').css("background", "#FFF");
}

function getRuleValue(ruleValue) {
    var tmpRuleVal = ruleValue.split(" ");
    return tmpRuleVal[2];
}

function getExtRuleInfo(ruleCategory, ruleValue, ruleScenario) {
    var tblTarget = $('#tblRuleInfo > tbody');
    var tRowTarget = tblTarget.children('tr');
    var strData = "{'RuleCategory':'" + ruleCategory + "', ";
    strData += "'RuleValue':'" + ruleValue + "', ";
    strData += "'RuleScenario':'" + ruleScenario + "'}";
    $.ajax({
        type: "POST",
        url: "ApprovalRule.aspx/ExtRuleInfo",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            var dataLength = data.d.length;
            if (dataLength > 0) {
                tRowTarget.eq(8).children('td').eq(2).find('span').text(data.d[0]);
                tRowTarget.eq(9).children('td').eq(2).find('span').text(data.d[1]);
                tRowTarget.eq(10).children('td').eq(2).find('span').text(data.d[2]);
            }
        }
    });
    return false;
}